<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class RuleController
 * @package Wintel\RestBundle\Controller
 */
class RuleController extends Controller
{
    /**
     * 获取日程规则
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", '');
        $rule_id  = $request->get("rule_id", 0);
        $info     = $request->get('info', '');

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 404, 'message'=>'info格式非json'));
            }
        }

        $where  = '';
        $where .= !empty($rule_id) ? " AND rule_id = :rule_id " : '';
        $params = !empty($rule_id) ? array('vcc_id'=>$vid, 'rule_id'=>$rule_id) : array('vcc_id'=>$vid);

        if (isset($addInfo['filter'])) {
            $where.= isset($addInfo['filter']['rule_name']) && !empty($addInfo['filter']['rule_name']) ? " AND rule_name like '%".$addInfo['filter']['rule_name']."%'" : '';
        }

        $count = $conn->fetchColumn(
            'SELECT count(*) FROM win_rules '.
            'WHERE vcc_id = :vcc_id '.$where,
            $params
        );

        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_rules', $addInfo);
        $page['sort'] = $page['sort'] !=1 ? $page['sort'] : $page['sort'];
        $list = $conn->fetchAll(
            'SELECT * FROM win_rules WHERE vcc_id = :vcc_id '.$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $params
        );
        $ret = array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     * 新建日程规则
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function addAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code   = $request->get('vcc_code', '');
        $rule_name  = $request->get('rule_name', '');
        $priority   = $request->get('priority', 1);
        $start_date = $request->get('start_date', '*');
        $end_date   = $request->get('end_date', '*');
        $start_time = $request->get('start_time', '*');
        $end_time   = $request->get('end_time', '*');
        $weeks      = $request->get('weeks', '0#1#2#3#4#5#6');
        $phone_id   = $request->get('phone_id', 0);
        $ivr_id     = $request->get('ivr_id', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证日程规则名称是否为空 */
        if (empty($rule_name)) {
            $ret = array(
                'code' => 403,
                'message' => '日程规则名称为空',
            );
            return new JsonResponse($ret);
        }

        /* 验证日程规则名称是否重复 */
        $where = " vcc_id = :vcc_id AND rule_name = :rule_name ";
        $par_arr = array('vcc_id'=>$vid, 'rule_name'=>$rule_name);
        $msg = $this->get('validator.custom')->existRule($where, $par_arr, 404);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        /* 获取所属号码信息 */
        $phone = $conn->fetchAssoc(
            'SELECT phone_id,phone,phone400 FROM cc_phone400s '.
            'WHERE vcc_id = :vcc_id AND phone_id = :phone_id',
            array('vcc_id'=>$vid,'phone_id'=>$phone_id)
        );

        if (empty($phone)) {
            $ret = array(
                'code' => 405,
                'message' => '所属号码为空',
            );
            return new JsonResponse($ret);
        }

        /* 获取IVR流程信息 */
        $ivr_info = $conn->fetchAssoc(
            'SELECT ivr_id,ivr_name,ivr_code FROM win_ivr '.
            'WHERE vcc_id = :vcc_id AND ivr_id = :ivr_id',
            array('vcc_id'=>$vid,'ivr_id'=>$ivr_id)
        );

        if (empty($ivr_info)) {
            $ret = array(
                'code' => 406,
                'message' => 'IVR流程为空',
            );
            return new JsonResponse($ret);
        }

        $data = array(
            'vcc_id' => $vid,
            'vcc_code' => $vcc_code,
            'rule_name' => $rule_name,
            'priority' => $priority,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'weeks' => $weeks,
            'add_time' => time(),
            'ivr_id' => $ivr_info['ivr_id'],
            'ivr_name' => $ivr_info['ivr_name'],
            'ivr_code' => $ivr_info['ivr_code'],
            'phone_id' => $phone['phone_id'],
            'phone' => $phone['phone'],
            'phone400' => $phone['phone400'],
        );

        try {
            $conn->insert('win_rules', $data);

            $ret = array(
                'code' => 200,
                'message' =>'ok'
            );
            return new JsonResponse($ret);

        } catch (Exception $e) {
            $ret = array(
                'code' => 407,
                'message' => '添加日程规则失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 编辑日程规则
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function editAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code   = $request->get('vcc_code', '');
        $rule_id    = $request->get("rule_id", 0);
        $rule_name  = $request->get('rule_name', '');
        $priority   = $request->get('priority', 1);
        $start_date = $request->get('start_date', '*');
        $end_date   = $request->get('end_date', '*');
        $start_time = $request->get('start_time', '*');
        $end_time   = $request->get('end_time', '*');
        $weeks      = $request->get('weeks', '0#1#2#3#4#5#6');
        $phone_id   = $request->get('phone_id', 0);
        $ivr_id     = $request->get('ivr_id', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证企业是否存在该日程规则 */
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_rules '.
            'WHERE vcc_id = :vcc_id AND rule_id = :rule_id ',
            array('vcc_id'=>$vid,'rule_id'=>$rule_id)
        );

        if (empty($count)) {
            $ret = array(
                'code' => 403,
                'message' => '日程规则不存在',
            );
            return new JsonResponse($ret);
        }
        /* 验证日程规则名称是否为空 */
        if (empty($rule_name)) {
            $ret = array(
                'code' => 404,
                'message' => '日程规则名称为空',
            );
            return new JsonResponse($ret);
        }

        /* 验证日程规则名称是否重复 */
        $where = " vcc_id = :vcc_id AND rule_name = :rule_name AND rule_id <> :rule_id";
        $par_arr = array('vcc_id'=>$vid, 'rule_name'=>$rule_name,'rule_id'=>$rule_id);
        $msg = $this->get('validator.custom')->existRule($where, $par_arr, 405);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        /* 获取所属号码信息 */
        $phone = $conn->fetchAssoc(
            'SELECT phone_id,phone,phone400 FROM cc_phone400s '.
            'WHERE vcc_id = :vcc_id AND phone_id = :phone_id',
            array('vcc_id'=>$vid,'phone_id'=>$phone_id)
        );

        if (empty($phone)) {
            $ret = array(
                'code' => 406,
                'message' => '所属号码为空',
            );
            return new JsonResponse($ret);
        }

        /* 获取IVR流程信息 */
        $ivr_info = $conn->fetchAssoc(
            'SELECT ivr_id,ivr_name,ivr_code FROM win_ivr '.
            'WHERE vcc_id = :vcc_id AND ivr_id = :ivr_id',
            array('vcc_id'=>$vid,'ivr_id'=>$ivr_id)
        );

        if (empty($ivr_info)) {
            $ret = array(
                'code' => 407,
                'message' => 'IVR流程为空',
            );
            return new JsonResponse($ret);
        }

        $data = array(
            'vcc_id' => $vid,
            'vcc_code' => $vcc_code,
            'rule_name' => $rule_name,
            'priority' => $priority,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'weeks' => $weeks,
            'add_time' => time(),
            'ivr_id' => $ivr_info['ivr_id'],
            'ivr_name' => $ivr_info['ivr_name'],
            'ivr_code' => $ivr_info['ivr_code'],
            'phone_id' => $phone['phone_id'],
            'phone' => $phone['phone'],
            'phone400' => $phone['phone400'],
        );

        try {
            $conn->update('win_rules', $data, array('vcc_id'=>$vid, 'rule_id'=>$rule_id));

            $ret = array(
                'code' => 200,
                'message' =>'ok'
            );
            return new JsonResponse($ret);

        } catch (Exception $e) {
            $ret = array(
                'code' => 408,
                'message' => '修改日程规则失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 删除日程规则
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code   = $request->get('vcc_code', '');
        $rule_id    = $request->get("rule_id", 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 有批量删除的情况 */
        $rule_arr = json_decode($rule_id);
        $rule_arr = json_last_error() || !is_array($rule_arr) ? array((int)$rule_id) : $rule_arr;
        if (empty($rule_arr)) {
            return new JsonResponse(array('code'=>403, 'message'=>'日程规则id为空'));
        }

        $errorMsg = array();

        foreach ($rule_arr as $rule_id) {
            try {
                $conn->delete('win_rules', array('vcc_id'=>$vid,'rule_id'=>$rule_id));

                $ret = array(
                    'code' => 200,
                    'message' => 'ok',
                );

                $errorMsg[] = array_merge($ret, array('rule_id'=>$rule_id));

            } catch (Exception $e) {
                $errorMsg[] = array(
                    'code' => 404,
                    'message' => '删除日程规则失败['.$e->getMessage().']',
                    'que_id' => $rule_id
                );
            }
        }

        return new JsonResponse(array('code'=>500,'message'=>'总结果','data'=>$errorMsg));
    }
}
